package com.talent.codes.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.oned.Code39Writer;
import com.google.zxing.oned.Code93Writer;
import com.google.zxing.oned.EAN13Writer;
import com.google.zxing.oned.UPCAWriter;
import com.google.zxing.oned.UPCEANWriter;
import com.google.zxing.oned.UPCEWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class CodeImageGenerator {

    public static void saveToFile(String filePath, byte[] content) throws IOException {
        // 将二维码图片保存到文件
        File file = new File(filePath);
        try(FileOutputStream fos = new FileOutputStream(file); ){
            fos.write(content);
        }
    }

    /**
     * 生成200*200的二维码图片并保存到指定路径, 前景色為黑色，背景色为白色
     *
     * @param data     要存储在二维码中的数据
     * @throws WriterException
     * @throws IOException
     */
    public static byte[] genQRCode(String data)
            throws WriterException, IOException {
        return genQRCode(data, 200, 200);
    }

    /**
     * 生成二维码图片, 前景色為黑色，背景色为白色
     *
     * @param data     要存储在二维码中的数据
     * @param width    图片宽度
     * @param height   图片高度
     * @throws WriterException
     * @throws IOException
     */
    public static byte[] genQRCode(String data, int width, int height)
            throws WriterException, IOException {
        return genQRCode(data, width, height, Color.BLACK, Color.WHITE);
    }

    /**
     * 生成二维码图片
     *
     * @param data     要存储在二维码中的数据
     * @param width    图片宽度
     * @param height   图片高度
     * @param frColor  前景色， black
     * @param bgColor  背景色   white
     * @throws WriterException 二维码生成失败时抛出
     * @throws IOException     图片写入失败时抛出
     */
    public static byte[] genQRCode(String data, int width, int height,
                                      Color frColor, Color bgColor) throws WriterException, IOException {
        if (frColor == null) frColor = Color.BLACK;
        if (bgColor == null) bgColor = Color.WHITE;

        if (width <= 10) width = 10;
        if (height <= 10) height = 10;

        // 设置二维码的编码参数
        Color.BLACK.getRGB();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 设置错误纠正级别为H
        hints.put(EncodeHintType.MARGIN, 0); // 设置二维码边距

        // 生成二维码的BitMatrix
        BitMatrix bitMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);

        // 创建BufferedImage对象来表示二维码
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? frColor.getRGB() : bgColor.getRGB());
            }
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        return os.toByteArray();
    }


    /**
     * 生成200*100的UPC_A条形码图片
     * @param data
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static byte[] genBarCodeEAN13(String data) throws WriterException, IOException {
        return genBarCode(data, BarcodeFormat.EAN_13, 200, 100);
    }


    /**
     * 生成200*100条形码图片
     * @param data          要存储在条形码中的数据
     * @param format        条形码格式，例如 Code128
     * @throws WriterException
     * @throws IOException
     */
    public static byte[] genBarCode(String data, BarcodeFormat format) throws WriterException, IOException {
        return genBarCode(data, format, 200, 100);
    }

    /**
     * 生成条形码图片
     *
     * @param data          要存储在条形码中的数据
     * @param format        条形码格式，例如 Code128
     * @throws WriterException 条形码生成失败时抛出
     * @throws IOException     图片写入失败时抛出
     */

    public static byte[] genBarCode(String data, BarcodeFormat format, int width, int height) throws WriterException, IOException {
        if (width <= 10) width = 10;
        if (height <= 10) height = 10;
        // 设置条形码的编码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码
        hints.put(EncodeHintType.MARGIN, 0); // 设置二维码边距

        // 生成条形码的BitMatrix
        Writer writer = new MultiFormatWriter();
        BitMatrix bitMatrix = writer.encode(data, format, width, height, hints);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", os);
        return os.toByteArray();
    }
}
